//
//  DataBaseManager.m
//  Shangri-La
//
//  Created by mac2 on 15-6-3.
//  Copyright (c) 2015年 huogenghao. All rights reserved.
//

#import "DataBaseManager.h"

#define MNDB_PATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"GB.db"]

#define FMDBQuickCheck(SomeBool) { if (!(SomeBool)) { NSLog(@"Failure on line %d", __LINE__); abort(); } }

#define GeebooDB @"book.db"
static DataBaseManager* dbConnection;

@interface DataBaseManager()
{
    NSLock *lock;
}
@end

@implementation DataBaseManager

+(id)shareInstance{
    NSLog(@"db:%@",MNDB_PATH);
    if (!dbConnection) {
        static dispatch_once_t token;
        dispatch_once(&token,^{
            dbConnection=[[DataBaseManager alloc]init];
        });
        
        
    }
    return dbConnection;
}

-(id)init{
    self=[super init];
    if (self) {
        lock = [[NSLock alloc]init];
        [self initBookDb];
    }
    
    return self;
}

-(NSString*)documentsDirectoryWithFileName:(NSString*)fileName
{
//    NSArray*	paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString*	documentsDirectory = [paths objectAtIndex:0];
    NSString*	directoryString = [MNDB_PATH stringByAppendingPathComponent:fileName];
    
    return	directoryString;
    
}

- (void)initBookDb {
    if (![[NSFileManager defaultManager] fileExistsAtPath:MNDB_PATH]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:MNDB_PATH withIntermediateDirectories:YES attributes:nil error:nil];
        _GeebooQueue= [FMDatabaseQueue databaseQueueWithPath:[self documentsDirectoryWithFileName:GeebooDB]];
        _GeebooDB= [FMDatabase databaseWithPath:[self documentsDirectoryWithFileName:GeebooDB]];
        [_GeebooDB open];
    } else {
        _GeebooQueue= [FMDatabaseQueue databaseQueueWithPath:[self documentsDirectoryWithFileName:GeebooDB]];
        _GeebooDB= [FMDatabase databaseWithPath:[self documentsDirectoryWithFileName:GeebooDB]];
        [_GeebooDB open];
    }
}


- (NSMutableArray *)dataBaseExecuteQuery:(NSString *)sql
{
    [lock lock];
    NSMutableArray *resultArray = [[NSMutableArray alloc]initWithCapacity:0];
    FMResultSet * set = [_GeebooDB executeQuery:sql];
    while ([set next]) {
        [resultArray addObject:[set resultDictionary]];
    }
    [lock unlock];
    return resultArray;
}

- (BOOL)dataBaseExecuteUpdate:(NSString *)sql
{
    [lock lock];
    BOOL isSuccess = [_GeebooDB executeUpdate:sql];
    [lock unlock];
    return isSuccess;
}

#pragma mark - 数据库更新

@end
